package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Setmeal;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealDao setmealDao;

    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Value("${out_put_path}")
    private String outPutPath; //从properties中读取要生成的html的目录
    @Override
    public int add(Setmeal setmeal, Integer[] checkgroupIds) {

        int codeCount = setmealDao.findCountByCode(setmeal.getCode());
        if (codeCount > 0) {
            throw new RuntimeException("套餐编码已存在！");
        }
        int nameCount = setmealDao.findCountByName(setmeal.getName());
        if (nameCount > 0) {
            throw new RuntimeException("套餐名称已存在！");
        }
        int count = setmealDao.add(setmeal);
        Integer setmeal_id = setmeal.getId();
        if (checkgroupIds !=null && checkgroupIds.length >0){
            setSetmealAndCheckGroup(checkgroupIds, setmeal_id);
        }
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());
        generateMobileStaticHtml();

        return count;
    }

    public void generateMobileStaticHtml(){
        List<Setmeal> setmealList = this.getSetmeal();
        generateMobileSetmealListHtml(setmealList);
        generateMobileSetmealDetailHtml(setmealList);
    }

    //生成套餐列表页面
    public void generateMobileSetmealListHtml(List<Setmeal> setmealList) {
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("setmealList",setmealList);
        this.generateHtml("mobile_setmeal.ftl","m_setmeal.html",dataMap);
    }


    //生成套餐详情页面
    public void generateMobileSetmealDetailHtml(List<Setmeal> setmealList) {
        for (Setmeal setmeal : setmealList) {
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("setmeal",this.findById(setmeal.getId()));
            this.generateHtml("mobile_setmeal_detail.ftl",
                    "setmeal_detail_"+setmeal.getId()+".html",dataMap);
        }
    }

    //通用生成静态页面
    public void generateHtml(String templateName,String htmlPageName,Map<String,Object> map){
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        OutputStreamWriter out = null;
        try {
            Template template = configuration.getTemplate(templateName);
            File docFile = new File(outPutPath+"\\" + htmlPageName);
            out = new OutputStreamWriter(new FileOutputStream(docFile),"utf-8");
            template.process(map,out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void setSetmealAndCheckGroup(Integer[] checkgroupIds, Integer setmeal_id) {
        Map<String, Integer> map = new HashMap<>();
        map.put("setmeal_id",setmeal_id);
        for (Integer checkgroup_id : checkgroupIds) {
            map.put("checkgroup_id",checkgroup_id);
            setmealDao.addSetmealAndCheckgroup(map);
        }
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        if (pageSize ==null || pageSize <1){
            pageSize = 10;
        }
        if (queryString == null||queryString.trim().equals("")){
            queryString="";
        }
        PageHelper.startPage(currentPage, pageSize);
        Page<Setmeal> page = setmealDao.findByCondition("%"+queryString.trim() +"%");
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public int deleteById(Integer id) {
        int count = 0;
        if (id != null){
            setmealDao.deleteSetmealAndCheckgroup(id);
            count = setmealDao.deleteSetmealById(id);
        }
        generateMobileStaticHtml();
        return count;
    }


//    展示套餐列表
    @Override
    public List<Setmeal> getSetmeal() {
        return setmealDao.findAll();
    }




    @Override
    public Setmeal findById(Integer id) {
        Setmeal setmeal = setmealDao.findById(id);
        return setmeal;
    }


    //获取套餐统计数据
    @Override
    public List<Map<String, Object>> findSetmealCount() {

        return setmealDao.findSetmealCount();
    }


}
